package com.zenithmind.document.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import com.zenithmind.document.pojo.dto.DocumentPermissionCreateDTO;
import com.zenithmind.document.pojo.dto.DocumentPermissionUpdateDTO;
import com.zenithmind.document.pojo.query.DocumentPermissionQueryDTO;
import com.zenithmind.document.pojo.vo.DocumentPermissionVO;
import com.zenithmind.document.service.DocumentPermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;

/**
 * 文档权限控制器
 * 遵循单一职责原则：专注于文档权限相关的HTTP接口
 * 遵循依赖倒置原则：依赖抽象服务接口
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/document/permission")
@RequiredArgsConstructor
@Validated
@Tag(name = "文档权限管理", description = "文档权限相关接口")
public class DocumentPermissionController {

    private final DocumentPermissionService documentPermissionService;

    @PostMapping
    @Operation(summary = "创建权限", description = "创建文档权限")
    public Result<DocumentPermissionVO> createPermission(@Valid @RequestBody DocumentPermissionCreateDTO createDTO) {
        log.info("创建权限请求: documentId={}", createDTO.getDocumentId());
        
        DocumentPermissionVO result = documentPermissionService.createPermission(createDTO);
        
        return Result.success(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新权限", description = "更新文档权限信息")
    public Result<Boolean> updatePermission(
            @Parameter(description = "权限ID", required = true) @PathVariable @NotBlank String id,
            @Valid @RequestBody DocumentPermissionUpdateDTO updateDTO) {
        
        log.info("更新权限请求: id={}", id);
        
        Boolean result = documentPermissionService.updatePermission(id, updateDTO);
        
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除权限", description = "删除文档权限")
    public Result<Boolean> deletePermission(
            @Parameter(description = "权限ID", required = true) @PathVariable @NotBlank String id) {
        
        log.info("删除权限请求: id={}", id);
        
        Boolean result = documentPermissionService.deletePermission(id);
        
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除权限", description = "批量删除文档权限")
    public Result<Boolean> batchDeletePermissions(
            @Parameter(description = "权限ID列表", required = true) @RequestBody @NotEmpty List<String> ids) {
        
        log.info("批量删除权限请求: ids={}", ids);
        
        Boolean result = documentPermissionService.batchDeletePermissions(ids);
        
        return Result.success(result);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询权限", description = "分页查询文档权限列表")
    public Result<IPage<DocumentPermissionVO>> getPermissionPage(@Valid DocumentPermissionQueryDTO queryDTO) {
        log.info("分页查询权限请求");
        
        IPage<DocumentPermissionVO> result = documentPermissionService.getPermissionPage(queryDTO);
        
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取权限详情", description = "获取文档权限详细信息")
    public Result<DocumentPermissionVO> getPermissionDetail(
            @Parameter(description = "权限ID", required = true) @PathVariable @NotBlank String id) {
        
        log.info("获取权限详情请求: id={}", id);
        
        DocumentPermissionVO result = documentPermissionService.getPermissionDetail(id);
        
        return Result.success(result);
    }

    @GetMapping("/document/{documentId}")
    @Operation(summary = "获取文档权限列表", description = "获取指定文档的权限列表")
    public Result<List<DocumentPermissionVO>> getDocumentPermissions(
            @Parameter(description = "文档ID", required = true) @PathVariable @NotBlank String documentId) {
        
        log.info("获取文档权限列表请求: documentId={}", documentId);
        
        List<DocumentPermissionVO> result = documentPermissionService.getDocumentPermissions(documentId);
        
        return Result.success(result);
    }

    @GetMapping("/user")
    @Operation(summary = "获取用户权限列表", description = "获取当前用户的权限列表")
    public Result<List<DocumentPermissionVO>> getUserPermissions() {
        log.info("获取用户权限列表请求");
        
        String userId = UserContext.getUserId();
        List<DocumentPermissionVO> result = documentPermissionService.getUserPermissions(userId);
        
        return Result.success(result);
    }

    @GetMapping("/check")
    @Operation(summary = "检查用户权限", description = "检查用户对文档的权限")
    public Result<Boolean> checkUserPermission(
            @Parameter(description = "文档ID", required = true) @RequestParam @NotBlank String documentId,
            @Parameter(description = "权限类型", required = true) @RequestParam @NotBlank String permission) {
        
        log.info("检查用户权限请求: documentId={}, permission={}", documentId, permission);
        
        String userId = UserContext.getUserId();
        Boolean result = documentPermissionService.checkUserPermission(documentId, userId, permission);
        
        return Result.success(result);
    }

    @GetMapping("/check-role")
    @Operation(summary = "检查角色权限", description = "检查角色对文档的权限")
    public Result<Boolean> checkRolePermission(
            @Parameter(description = "文档ID", required = true) @RequestParam @NotBlank String documentId,
            @Parameter(description = "角色ID", required = true) @RequestParam @NotBlank String roleId,
            @Parameter(description = "权限类型", required = true) @RequestParam @NotBlank String permission) {
        
        log.info("检查角色权限请求: documentId={}, roleId={}, permission={}", documentId, roleId, permission);
        
        Boolean result = documentPermissionService.checkRolePermission(documentId, roleId, permission);
        
        return Result.success(result);
    }

    @PostMapping("/grant-user")
    @Operation(summary = "授予用户权限", description = "授予用户对文档的权限")
    public Result<Boolean> grantUserPermissions(
            @Parameter(description = "文档ID", required = true) @RequestParam @NotBlank String documentId,
            @Parameter(description = "用户ID", required = true) @RequestParam @NotBlank String userId,
            @Parameter(description = "权限列表", required = true) @RequestBody @NotEmpty List<String> permissions) {
        
        log.info("授予用户权限请求: documentId={}, userId={}, permissions={}", documentId, userId, permissions);
        
        String grantorId = UserContext.getUserId();
        Boolean result = documentPermissionService.grantUserPermissions(documentId, userId, permissions, grantorId);
        
        return Result.success(result);
    }

    @PostMapping("/revoke-user")
    @Operation(summary = "撤销用户权限", description = "撤销用户对文档的权限")
    public Result<Boolean> revokeUserPermissions(
            @Parameter(description = "文档ID", required = true) @RequestParam @NotBlank String documentId,
            @Parameter(description = "用户ID", required = true) @RequestParam @NotBlank String userId,
            @Parameter(description = "权限列表", required = true) @RequestBody @NotEmpty List<String> permissions) {
        
        log.info("撤销用户权限请求: documentId={}, userId={}, permissions={}", documentId, userId, permissions);
        
        Boolean result = documentPermissionService.revokeUserPermissions(documentId, userId, permissions);
        
        return Result.success(result);
    }

    @PostMapping("/grant-role")
    @Operation(summary = "授予角色权限", description = "授予角色对文档的权限")
    public Result<Boolean> grantRolePermissions(
            @Parameter(description = "文档ID", required = true) @RequestParam @NotBlank String documentId,
            @Parameter(description = "角色ID", required = true) @RequestParam @NotBlank String roleId,
            @Parameter(description = "权限列表", required = true) @RequestBody @NotEmpty List<String> permissions) {
        
        log.info("授予角色权限请求: documentId={}, roleId={}, permissions={}", documentId, roleId, permissions);
        
        String grantorId = UserContext.getUserId();
        Boolean result = documentPermissionService.grantRolePermissions(documentId, roleId, permissions, grantorId);
        
        return Result.success(result);
    }

    @PostMapping("/revoke-role")
    @Operation(summary = "撤销角色权限", description = "撤销角色对文档的权限")
    public Result<Boolean> revokeRolePermissions(
            @Parameter(description = "文档ID", required = true) @RequestParam @NotBlank String documentId,
            @Parameter(description = "角色ID", required = true) @RequestParam @NotBlank String roleId,
            @Parameter(description = "权限列表", required = true) @RequestBody @NotEmpty List<String> permissions) {
        
        log.info("撤销角色权限请求: documentId={}, roleId={}, permissions={}", documentId, roleId, permissions);
        
        Boolean result = documentPermissionService.revokeRolePermissions(documentId, roleId, permissions);
        
        return Result.success(result);
    }

    @PostMapping("/copy")
    @Operation(summary = "复制权限", description = "复制文档权限到另一个文档")
    public Result<Boolean> copyPermissions(
            @Parameter(description = "源文档ID", required = true) @RequestParam @NotBlank String sourceDocumentId,
            @Parameter(description = "目标文档ID", required = true) @RequestParam @NotBlank String targetDocumentId) {
        
        log.info("复制权限请求: sourceDocumentId={}, targetDocumentId={}", sourceDocumentId, targetDocumentId);
        
        Boolean result = documentPermissionService.copyPermissions(sourceDocumentId, targetDocumentId);
        
        return Result.success(result);
    }

    @PostMapping("/inherit")
    @Operation(summary = "继承权限", description = "继承父文档的权限")
    public Result<Boolean> inheritPermissions(
            @Parameter(description = "父文档ID", required = true) @RequestParam @NotBlank String parentDocumentId,
            @Parameter(description = "子文档ID", required = true) @RequestParam @NotBlank String childDocumentId) {
        
        log.info("继承权限请求: parentDocumentId={}, childDocumentId={}", parentDocumentId, childDocumentId);
        
        Boolean result = documentPermissionService.inheritPermissions(parentDocumentId, childDocumentId);
        
        return Result.success(result);
    }

    @PostMapping("/set-default")
    @Operation(summary = "设置默认权限", description = "设置文档的默认权限")
    public Result<Boolean> setDefaultPermissions(
            @Parameter(description = "文档ID", required = true) @RequestParam @NotBlank String documentId,
            @Parameter(description = "权限配置", required = true) @RequestBody Object permissions) {
        
        log.info("设置默认权限请求: documentId={}", documentId);
        
        Boolean result = documentPermissionService.setDefaultPermissions(documentId, permissions);
        
        return Result.success(result);
    }

    @GetMapping("/effective")
    @Operation(summary = "获取有效权限", description = "获取用户对文档的有效权限")
    public Result<List<String>> getEffectivePermissions(
            @Parameter(description = "文档ID", required = true) @RequestParam @NotBlank String documentId) {
        
        log.info("获取有效权限请求: documentId={}", documentId);
        
        String userId = UserContext.getUserId();
        List<String> result = documentPermissionService.getEffectivePermissions(documentId, userId);
        
        return Result.success(result);
    }

    @GetMapping("/tree/{documentId}")
    @Operation(summary = "获取权限树", description = "获取文档权限树结构")
    public Result<Object> getPermissionTree(
            @Parameter(description = "文档ID", required = true) @PathVariable @NotBlank String documentId) {
        
        log.info("获取权限树请求: documentId={}", documentId);
        
        Object result = documentPermissionService.getPermissionTree(documentId);
        
        return Result.success(result);
    }

    @PostMapping("/batch-set")
    @Operation(summary = "批量设置权限", description = "批量设置多个文档的权限")
    public Result<Boolean> batchSetPermissions(
            @Parameter(description = "文档ID列表", required = true) @RequestBody @NotEmpty List<String> documentIds,
            @Parameter(description = "权限配置", required = true) @RequestBody Object permissions) {
        
        log.info("批量设置权限请求: documentIds={}", documentIds);
        
        Boolean result = documentPermissionService.batchSetPermissions(documentIds, permissions);
        
        return Result.success(result);
    }

    @PostMapping("/cleanup")
    @Operation(summary = "清理过期权限", description = "清理过期的权限配置")
    public Result<Integer> cleanupExpiredPermissions() {
        log.info("清理过期权限请求");
        
        Integer result = documentPermissionService.cleanupExpiredPermissions();
        
        return Result.success(result);
    }

    @GetMapping("/audit/{documentId}")
    @Operation(summary = "权限审计", description = "对文档权限进行审计")
    public Result<Object> auditPermissions(
            @Parameter(description = "文档ID", required = true) @PathVariable @NotBlank String documentId) {
        
        log.info("权限审计请求: documentId={}", documentId);
        
        Object result = documentPermissionService.auditPermissions(documentId);
        
        return Result.success(result);
    }

    @GetMapping("/change-history/{documentId}")
    @Operation(summary = "获取权限变更历史", description = "获取文档权限变更历史")
    public Result<List<Object>> getPermissionChangeHistory(
            @Parameter(description = "文档ID", required = true) @PathVariable @NotBlank String documentId,
            @Parameter(description = "限制数量") @RequestParam(required = false, defaultValue = "20") Integer limit) {
        
        log.info("获取权限变更历史请求: documentId={}, limit={}", documentId, limit);
        
        List<Object> result = documentPermissionService.getPermissionChangeHistory(documentId, limit);
        
        return Result.success(result);
    }

    @GetMapping("/export/{documentId}")
    @Operation(summary = "导出权限配置", description = "导出文档权限配置")
    public Result<Object> exportPermissionConfig(
            @Parameter(description = "文档ID", required = true) @PathVariable @NotBlank String documentId) {
        
        log.info("导出权限配置请求: documentId={}", documentId);
        
        Object result = documentPermissionService.exportPermissionConfig(documentId);
        
        return Result.success(result);
    }

    @PostMapping("/import/{documentId}")
    @Operation(summary = "导入权限配置", description = "导入文档权限配置")
    public Result<Boolean> importPermissionConfig(
            @Parameter(description = "文档ID", required = true) @PathVariable @NotBlank String documentId,
            @Parameter(description = "权限配置", required = true) @RequestBody Object config) {
        
        log.info("导入权限配置请求: documentId={}", documentId);
        
        Boolean result = documentPermissionService.importPermissionConfig(documentId, config);
        
        return Result.success(result);
    }

    @PostMapping("/validate")
    @Operation(summary = "验证权限配置", description = "验证权限配置的有效性")
    public Result<Object> validatePermissionConfig(
            @Parameter(description = "权限配置", required = true) @RequestBody Object config) {
        
        log.info("验证权限配置请求");
        
        Object result = documentPermissionService.validatePermissionConfig(config);
        
        return Result.success(result);
    }

    @GetMapping("/templates")
    @Operation(summary = "获取权限模板", description = "获取权限模板列表")
    public Result<List<Object>> getPermissionTemplates() {
        log.info("获取权限模板请求");
        
        List<Object> result = documentPermissionService.getPermissionTemplates();
        
        return Result.success(result);
    }

    @PostMapping("/apply-template")
    @Operation(summary = "应用权限模板", description = "应用权限模板到文档")
    public Result<Boolean> applyPermissionTemplate(
            @Parameter(description = "文档ID", required = true) @RequestParam @NotBlank String documentId,
            @Parameter(description = "模板ID", required = true) @RequestParam @NotBlank String templateId) {
        
        log.info("应用权限模板请求: documentId={}, templateId={}", documentId, templateId);
        
        Boolean result = documentPermissionService.applyPermissionTemplate(documentId, templateId);
        
        return Result.success(result);
    }

    @PostMapping("/create-template")
    @Operation(summary = "创建权限模板", description = "创建新的权限模板")
    public Result<String> createPermissionTemplate(
            @Parameter(description = "模板名称", required = true) @RequestParam @NotBlank String name,
            @Parameter(description = "权限配置", required = true) @RequestBody Object config) {
        
        log.info("创建权限模板请求: name={}", name);
        
        String result = documentPermissionService.createPermissionTemplate(name, config);
        
        return Result.success(result);
    }

    @GetMapping("/statistics/{documentId}")
    @Operation(summary = "获取权限统计", description = "获取文档权限统计信息")
    public Result<Object> getPermissionStatistics(
            @Parameter(description = "文档ID", required = true) @PathVariable @NotBlank String documentId) {
        
        log.info("获取权限统计请求: documentId={}", documentId);
        
        Object result = documentPermissionService.getPermissionStatistics(documentId);
        
        return Result.success(result);
    }

    @PostMapping("/sync/{documentId}")
    @Operation(summary = "同步权限", description = "同步文档权限数据")
    public Result<Boolean> syncPermissions(
            @Parameter(description = "文档ID", required = true) @PathVariable @NotBlank String documentId) {
        
        log.info("同步权限请求: documentId={}", documentId);
        
        Boolean result = documentPermissionService.syncPermissions(documentId);
        
        return Result.success(result);
    }
}
